/**
 * author by @wzs 2018-02-03
 * api改写为promise写法,更好的做异步
 */
var http = require('http');
var https = require('https');
var querystring = require('querystring');
var utility = require("./utility");
var logger =require("./logger").logger('api-helper');
var timehash = require("com.zoe.timehash").timehash;
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));

var apiFun={
    getPlatformApi(path,parameter,req,res){
        return new Promise(function(resolve, reject){
            var token = req.session.token === undefined?"":req.session.token;
            if(parameter === null){
                parameter = utility.extend(req.query,req.body);
            }else{
                parameter = JSON.parse(parameter);
            }
            parameter.token = token;
            parameter = {parameter:JSON.stringify(parameter),token:token};
            var option={
                url:path,
                method: 'POST',
                data:parameter
            };
            //Print request log
            console.log("time-hash:"+timehash()+" ; Request address and parameters:"+path+"?"+decodeURIComponent(querystring.stringify(option.data)));
            apiFun.getApi(option).then((data)=>{
                resolve(data);
            }).catch((err)=>{
                reject(err);
            });
        });

    },
    getApi(opt){
        return new Promise(function(resolve, reject){
            const option = {
                method: opt.method || 'POST',
                url: opt.url || '',
                headers: {
                    "time-hash": timehash()
                },
                json: true
            };
            if(option.method === 'POST'){
                option.body = opt.data || {};
            }
            request(option).then(function(response){
                if(response.statusCode === 200){
                    var _data = response['body'];
                    resolve(_data);
                }else{
                    throw new Error('Request time out,Request address and parameters::'+opt.url);
                }
            }).catch(function(err){
                reject(err);
            });
        });
    },
};
module.exports = apiFun;